﻿
using System.ComponentModel;
using System.Windows.Data;

namespace MvvmFx.Common.Helpers
{
    /// <summary>
    /// The BindingHelper class.
    /// </summary>
    public class BindingHelper : INotifyPropertyChanged
    {
        /// <summary>
        /// The _value field.
        /// </summary>
        private object _value;

        /// <summary>
        /// The property changed handler.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Gets or sets the value of the <see cref="Value"/> property.
        /// </summary>
        public object Value
        {
            get
            {
                return this._value;
            }

            set
            {
                if (this._value != value)
                {
                    this._value = value;
                    this.OnPropertyChanged("Value");
                }
            }
        }

        /// <summary>
        /// Create the binding.
        /// </summary>
        /// <param name="bindingHelperResource">The binding helper to create the binding.</param>
        /// <returns>The binding created.</returns>
        public static Binding Bind(object bindingHelperResource)
        {
            BindingHelper helper = (BindingHelper)bindingHelperResource;
            return helper.Bind();
        }

        /// <summary>
        /// Create the binding.
        /// </summary>
        /// <returns>The binding created.</returns>
        public Binding Bind()
        {
            Binding binding = 
                new Binding("Value")
                    {
                        Source = this, 
                        Mode = BindingMode.TwoWay
                    };
            return binding;
        }

        /// <summary>
        /// On the specified property changing.
        /// </summary>
        /// <param name="propertyName">The name of the property changing.</param>
        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}